﻿using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Text;
using Jeelu.Exceptions;

namespace Jeelu.Wrapper
{
    public class CsvFile
    {
        /// <summary>
        /// 把DataTable的数据导出到CSV文件中
        /// </summary>
        /// <param name="dataTable">导出CSV的数据</param>
        /// <param name="savePath">导出的路径</param>
        public static bool DatatableToCsvFile(DataTable dataTable, string savePath)
        {
            if (dataTable == null)
                throw new ArgumentNullException("dataTable");
            if (savePath == null)
                throw new ArgumentNullException("savePath");
            try
            {
                using (FileStream fs = File.Create(savePath))
                {
                    var sw = new StreamWriter(fs, Encoding.Default);
                    var caption = new StringBuilder();
                    for (int i = 0; i < dataTable.Columns.Count; i++)
                    {
                        if (i != dataTable.Columns.Count - 1)
                            caption.Append(dataTable.Columns[i].Caption).Append(',');
                        else
                            caption.Append(dataTable.Columns[i].Caption);
                    }
                    sw.WriteLine(caption.ToString());

                    foreach (DataRow dr in dataTable.Rows)
                    {
                        var row = new StringBuilder();
                        for (int i = 0; i < dataTable.Columns.Count; i++)
                        {
                            string tmp;
                            if (i != dataTable.Columns.Count - 1)
                            {
                                tmp = dr[i].ToString().Trim().Replace(",", " ");
                                row.Append(tmp).Append(",");
                            }
                            else
                            {
                                tmp = dr[i].ToString().Trim().Replace(",", ".");
                                row.Append(tmp);
                            }
                        }
                        sw.WriteLine(row);
                    }
                    sw.Flush();
                    sw.Close();
                } //using
                return true;
            }
            catch (Exception ex)
            {
                throw new CsvFileOperationException(ex);
            }
        }
    }
}
